/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.kongfuzi.student.support.volley.toolbox;

import android.text.TextUtils;

import com.kongfuzi.student.app.GasApplication;
import com.kongfuzi.student.bean.Cache;
import com.kongfuzi.student.support.utils.ToastUtil;
import com.kongfuzi.student.support.volley.NetworkResponse;
import com.kongfuzi.student.support.volley.Request;
import com.kongfuzi.student.support.volley.VolleyLog;
import com.kongfuzi.student.support.utils.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.DbException;

import java.io.UnsupportedEncodingException;
import java.util.List;

import com.kongfuzi.student.support.volley.Response;
import com.kongfuzi.student.support.volley.Response.ErrorListener;
import com.kongfuzi.student.support.volley.Response.Listener;

/**
 * A request for retrieving a T type response body at a given URL that also
 * optionally sends along a JSON body in the request specified.
 *
 * @param <T> JSON type of response expected
 */
public abstract class JsonRequest<T> extends Request<T> {
    /**
     * Default charset for JSON request.
     */
    protected static final String PROTOCOL_CHARSET = "utf-8";

    /**
     * Content type for request.
     */
    private static final String PROTOCOL_CONTENT_TYPE =
            String.format("application/json; charset=%s", PROTOCOL_CHARSET);

    private final Listener<T> mListener;
    private final String mRequestBody;
    private boolean needCache = false;

    /**
     * Deprecated constructor for a JsonRequest which defaults to GET unless {@link #getPostBody()}
     * or {@link #getPostParams()} is overridden (which defaults to POST).
     *
     * @deprecated Use {@link #JsonRequest(int, String, String, Listener, ErrorListener)}.
     */
    public JsonRequest(String url, String requestBody, Listener<T> listener,
                       ErrorListener errorListener) {
        this(Method.DEPRECATED_GET_OR_POST, url, requestBody, listener, errorListener);
    }

    public JsonRequest(int method, String url, String requestBody, Listener<T> listener,
                       ErrorListener errorListener) {
        super(method, url, errorListener);
        mListener = listener;
        mRequestBody = requestBody;
    }

    /**
     * 增加了needCache的重载方法
     */
    public JsonRequest(int method, String url, String requestBody, Listener<T> listener,
                       ErrorListener errorListener, boolean needCache) {
        //为所有请求的接口加上token
        super(method, url + "&token=" + GasApplication.getSecretkey(), errorListener);
        mListener = listener;
        mRequestBody = requestBody;
        this.needCache = needCache;
        //如果需要缓存，则先取出之前的缓存
        if (needCache) {
            url = url + "&token=" + GasApplication.getSecretkey();
            try {
                List<Cache> datas = GasApplication.getCacheDbManager().selector(Cache.class).where("requestUrl", "=", url).orderBy("time", false).limit(1)
                        .findAll();
                if (datas != null && listener != null) {
                    for (Cache cache : datas) {
                        listener.onResponse((T) new JSONObject(cache.jsonString));
                    }
                }
            } catch (DbException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    protected void deliverResponse(final T response) {
        mListener.onResponse(response);
        if (needCache&&response != null
                && (response.getClass().equals(String.class) || response.getClass().equals
                (JSONObject.class))) {
            new Thread() {
                @Override
                public void run() {
                    Cache cache = new Cache(mUrl,response.toString());
                    try {
                        GasApplication.getCacheDbManager().save(cache);
                        LogUtil.showInfoLog("save", "save success");
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
        if(response!=null && response.getClass().equals(JSONObject.class)) {//确保返回的是JSON
            JSONObject result = (JSONObject) response;
            if(!result.optBoolean("success")) {//服务器返回失败信息
                if(!TextUtils.isEmpty(result.optString("message"))) {
                    ToastUtil.showToast(GasApplication.getInstance(), result.optString("message"));
                }
            }
        }
    }

    @Override
    abstract protected Response<T> parseNetworkResponse(NetworkResponse response);

    /**
     * @deprecated Use {@link #getBodyContentType()}.
     */
    @Override
    public String getPostBodyContentType() {
        return getBodyContentType();
    }

    /**
     * @deprecated Use {@link #getBody()}.
     */
    @Override
    public byte[] getPostBody() {
        return getBody();
    }

    @Override
    public String getBodyContentType() {
        return PROTOCOL_CONTENT_TYPE;
    }

    @Override
    public byte[] getBody() {
        try {
            return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                    mRequestBody, PROTOCOL_CHARSET);
            return null;
        }
    }
}
